package com.bvr;

import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class EarningsActivity extends ListActivity {

	private ProgressDialog m_ProgressDialog = null;
	private ArrayList<EarningObject> m_earnings = null;
	private EarningObjectAdapter m_adapter;
	private Runnable viewOrders;
	private Thread thread;

	AlertDialog alertPaging;
	private static CharSequence[] itemsParent;

	private static Integer UserID = 0;
	private static String RANGE = "1-10";
	private static Integer totalRecords;
	private static Integer recordsPerPage;

	private static String URL = "";
	private static String METHOD_NAME = "";
	private static String NAMESPACE = "";
	private static String SOAP_ACTION = "";

	//private TextView lblNoProperty;
	//private TextView lblPaging;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.earnings);
		setVariables();

		m_earnings = new ArrayList<EarningObject>();
		this.m_adapter = new EarningObjectAdapter(this, R.layout.earning_row,
				m_earnings);
		setListAdapter(this.m_adapter);

		viewOrders = new Runnable() {
			@Override
			public void run() {
				getProperties();
			}
		};

		if (isNetworkAvailable()) {
			//lblNoProperty.setText("");
			thread = new Thread(null, viewOrders, "MagentoBackground");
			thread.start();
			m_ProgressDialog = ProgressDialog.show(EarningsActivity.this,
					"Please wait...", "Retrieving data ...", true);
			m_adapter.notifyDataSetChanged();
		} else {
			//lblNoProperty
			//		.setText("No active connection found, please check your internet connection");
		}

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.properties_list_menu, menu);
	    return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    case R.id.menu_refresh:
	    	
	    	if (isNetworkAvailable()) {
	    		m_adapter.clear();
				//lblNoProperty.setText("");
				thread = new Thread(null, viewOrders, "MagentoBackground");
				thread.start();
				m_ProgressDialog = ProgressDialog.show(EarningsActivity.this,
						"Please wait...", "Retrieving data ...", true);
			} else {
				//lblNoProperty
				//		.setText("No active connection found, please check your internet connection");
			}
	        
	    	Log.e("Menu Click", "Exit Menu Clicked");
	        return true;
	    case R.id.menu_more:
	    	alertPaging.show();
	    	Log.e("Menu Click", "Preferences Menu Clicked");
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		// Get the item that was clicked
		Object o = this.getListAdapter().getItem(position);
	
		EarningObject _earning = m_earnings.get(position);
		Intent detailActivityIntent = new Intent(v.getContext(),
				EarningActivty.class);	
		
		EarningActivty._earning = _earning;				
		startActivityForResult(detailActivityIntent, 0);
	}

	private void getProperties() {
		try {
			m_earnings = new ArrayList<EarningObject>();

			ParseWebService();
			Log.i("ARRAY", "" + m_earnings.size());
		} catch (Exception e) {
			Log.e("BACKGROUND_PROC", e.getMessage());
		}
		runOnUiThread(returnRes);
	}

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			if (m_earnings != null && m_earnings.size() > 0) {
				m_adapter.notifyDataSetChanged();
				for (int i = 0; i < m_earnings.size(); i++)
					m_adapter.add(m_earnings.get(i));
			} else {
				//lblNoProperty.setText(getText(R.string.main_no_items));
			}
			thread.stop();
			m_ProgressDialog.dismiss();			
			m_adapter.notifyDataSetChanged();
			//lblPaging.setText(RANGE);
		}
	};

	/* Web Service Parsing */


	private void ParseWebService() throws IOException, XmlPullParserException,
			JSONException {

		SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("ownerID", UserID);
		request.addProperty("range", RANGE);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.dotNet = true;

		envelope.implicitTypes = true;
		envelope.encodingStyle = "utf-8";
		envelope.enc = SoapSerializationEnvelope.ENC2001;
		envelope.xsd = SoapEnvelope.XSD;
		envelope.xsi = SoapEnvelope.XSI;

		envelope.setOutputSoapObject(request);
		AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(
				URL);
		envelope.addMapping(NAMESPACE, "Properties",
				new PropertyObject().getClass());
		androidHttpTransport.call(SOAP_ACTION, envelope);
		androidHttpTransport
				.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

		androidHttpTransport.debug = true;
		SoapObject soapresultmsg = (SoapObject) envelope.getResponse();
		SoapObject recordsArray = (SoapObject) soapresultmsg.getProperty(0);
		int recordCount = recordsArray.getPropertyCount();
		// debugDisplay("Records ka Count hai : " +
		// Integer.toString(recordCount));
		m_earnings = new ArrayList<EarningObject>();
		try {
			for (int i = 0; i < recordCount; i++) {
				EarningObject property = new EarningObject();
				Ksoap2ResultParser.parseBusinessObject(recordsArray
						.getProperty(i).toString(), property);
				m_earnings.add(property);
			}

		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void setVariables() {
		//lblNoProperty = (TextView) findViewById(R.id.noProperty);
		//lblPaging = (TextView) findViewById(R.id.propertyPaging);

		SharedPreferences appSettings = getSharedPreferences(
				"BVRAppPreferences", MODE_PRIVATE);
		String ownerID = appSettings.getString("ownerID", "0");
		UserID = Integer.parseInt(ownerID);
		// UserID = 723; // Integer.parseInt(ownerID);

		recordsPerPage = Integer.parseInt(getString(R.string.records_per_page));
		totalRecords = Integer.parseInt(appSettings.getString("propertyCount",
				"0"));

		RANGE = "1-" + getString(R.string.records_per_page);
		URL = getString(R.string.url_earning);
		METHOD_NAME = getString(R.string.method_name_earning);
		NAMESPACE = getString(R.string.namespace_earning);
		SOAP_ACTION = getString(R.string.soap_action_earning);

		setPagingAlert();
	}	

	private void getPagingItems() {
		int startValue, endValue, remainder, numberOfPages;
		numberOfPages = totalRecords / recordsPerPage;
		remainder = totalRecords % recordsPerPage;
		startValue = 1;
		endValue = recordsPerPage;
		if (remainder == 0) {
			CharSequence[] items = new CharSequence[numberOfPages];

			for (int a = 0; a < numberOfPages; a++) {
				items[a] = String.valueOf(startValue).toString() + "-"
						+ String.valueOf(endValue).toString();
				startValue = endValue + 1;
				endValue = endValue + recordsPerPage;
			}
			itemsParent = items;
		} else {
			CharSequence[] items = new CharSequence[numberOfPages + 1];
			for (int a = 0; a < numberOfPages; a++) {
				items[a] = String.valueOf(startValue).toString() + "-"
						+ String.valueOf(endValue).toString();
				startValue = endValue + 1;
				endValue = endValue + recordsPerPage;
			}

			if (startValue == totalRecords) {
				items[numberOfPages] = String.valueOf(startValue).toString()
						+ "-" + String.valueOf(startValue).toString();
			} else {
				items[numberOfPages] = String.valueOf(startValue).toString()
						+ "-"
						+ String.valueOf(startValue + (remainder - 1))
								.toString();
			}
			itemsParent = items;
		}
		// return itemsParent;
	}

	private void setPagingAlert() {
		getPagingItems();
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pick A Range");
		builder.setCancelable(true);
		builder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

		builder.setSingleChoiceItems(itemsParent, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						doPagingAction(item);
					}
				});
		alertPaging = builder.create();
	}

	private void doPagingAction(int indx) {
		m_adapter.clear();
		alertPaging.dismiss();
		//debugDisplay(itemsParent[indx].toString() + " : Selected");
		RANGE = itemsParent[indx].toString();

		/**
		 * viewOrders = new Runnable() {
		 * 
		 * @Override public void run() { getProperties(); } };
		 */
		Thread thread = new Thread(null, viewOrders, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(EarningsActivity.this,
				"Please wait...", "Retrieving data ...", true);
		m_adapter.notifyDataSetChanged();

	}

	public void debugDisplay(String s) {
		System.out.println(s);
	}

}
